package com.onluy.frameworkcloud.system.resolver;


import java.io.BufferedReader;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.onluy.frameworkcloud.data.util.InParam;

import javax.servlet.http.HttpServletRequest;

public class InParamMethodArgumentResolver extends BaseMethodArgumentResolver
  implements HandlerMethodArgumentResolver
{
  protected Logger log =   LoggerFactory.getLogger(this.getClass());



  public boolean supportsParameter(MethodParameter parameter)
  {
    return InParam.class.isAssignableFrom(parameter.getParameterType());
  }

  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception
  {
    InParam inParam = new InParam();
    Iterator fields = webRequest.getParameterNames();
    HttpServletRequest httpServletRequest =  webRequest.getNativeRequest(HttpServletRequest.class);
    StringBuffer loginf = new StringBuffer();
    loginf.append(  System.getProperty("line.separator"));
    loginf.append("请求URL :" + httpServletRequest.getRequestURI().replace( httpServletRequest.getContextPath(),"") + System.getProperty("line.separator"));
    loginf.append("请求URL参数:" + httpServletRequest.getQueryString() + System.getProperty("line.separator"));
    loginf.append("请求方式:" + httpServletRequest.getMethod() + System.getProperty("line.separator"));
    loginf.append("请求数据CharacterEncoding:" + httpServletRequest.getCharacterEncoding() + System.getProperty("line.separator"));
    this.log.info(loginf.toString());

    StringBuffer json = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = httpServletRequest.getReader();

      while((line = reader.readLine()) != null) {
        json.append(line);
      }
    } catch (Exception var17) {
      ;
    }
    log.info(" >>>>>>>>>>>>>>>>>>>> InParamMethodArgumentResolver post data   : "+json);

    while (fields.hasNext()) {
      String field = (String)fields.next();
      String[] values = webRequest.getParameterValues(field);
      if (values.length > 1) {
        inParam.put(field, values);
      }
      else if (!StringUtils.isEmpty(values[0])) {
        inParam.put(field, values[0]);
      }

    }

    log.info(" >>>>>>>>>>>>>>>>>>>> InParamMethodArgumentResolver.inParam  : "+inParam.toString());



    return inParam;
  }
}